package hospital.action;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import hospital.model.AppointmentModel;
import hospital.model.DocScheduleModel;
import hospital.model.LoginModel;
import hospital.model.PatientInfoModel;
import hospital.model.EmpInfoModel;
import hospital.model.RecordDetailModel;
import hospital.service.StaffService;
import hospital.util.HospitalUtil;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

public class StaffOperation extends ActionSupport implements Preparable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -759096089346921676L;

	private HospitalUtil hospitalUtil;
	private PatientInfoModel patientInfo;
	private String firstname;
	private String lastname;
	private String email;
	private String sin;
	private String ohip;
	private String gender;
	private String phoneNum;
	private String cellphone;
	private String address;
	private String postalCode;
	private String defaultDoctor;
	private String date;
	private String time;
	private String year;
	private String month;
	private String day;
	private String hour;
	private String minute;
	private String currentHealth;
	private StaffService staffService;
	private LoginModel loginInfo;

	private String searchUserId;
	private String searchFirstname;
	private String searchLastname;
	private List<PatientInfoModel> patientSearchResult;

	private String appointPatientId;
	private String appointPatientFirstname;
	private String appointPatientLastname;
	private List<PatientInfoModel> appointPatientSearchResult;

	private String appointDocId;
	private String appointDocFirstname;
	private String appointDocLastname;
	private List<EmpInfoModel> appointDocSearchResult;

	private String confirmedPatientId;
	private String confirmedDocId;

	private String scheduleDocId;
	private List<DocScheduleModel> docSchedules;

	private AppointmentModel appointment;

	private String recordListPatientId;
	private List<RecordDetailModel> recordDetailList;

	private String appointmentId;

	private String updateAppointId;
	private String deleteAppointId;

	private String updatePatientId;

	private String recordPatientId;
	private String yearStart;
	private String monthStart;
	private String dayStart;
	private String yearEnd;
	private String monthEnd;
	private String dayEnd;
	private String recordDiagnosis;
	private String recordDrug;
	private String recordComment;

	private boolean flag;
	private String message;

	private String relistAppointmentId;
	private String relistPatientId;
	private String relistDocId;

	private String startDate;
	private String endDate;

	private String origPassword;
	private String newPassword;
	private String confirmedNewPassword;

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
			+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	private static final String POSTALCODE_PATTERN = "^[A-Z]{1}\\d{1}[A-Z]{1}\\d{1}[A-Z]{1}\\d{1}$";
	private static final String PHONE_PATTERN = "\\d{10}";
	private static final String SIN_PATTERN = "\\d{9}";
	private static final String OHIP_PATTERN = "\\d{10}($|[A-Z]{2})";

	@Override
	public void prepare() throws Exception {
		clearActionErrors();
		clearFieldErrors();
	}

	public String newPatient() {
		return SUCCESS;
	}

	public String changePassword() {
		String encryptedPw = staffService.checkPassword();
		if (encryptedPw.equals(hospitalUtil.encrypt(origPassword))) {
			if (newPassword.length() < 6) {
				flag = false;
				message = "Password needs to be at least 6 characters long";
				return SUCCESS;
			}
			if (newPassword.equals(confirmedNewPassword)) {
				boolean result = staffService.changePassword(newPassword);
				if (result) {
					flag = true;
					message = "Change password successfully.";
					return SUCCESS;
				} else {
					flag = false;
					message = "Fail to change password.";
					return SUCCESS;
				}
			} else {
				flag = false;
				message = "New passwords do not match.";
				return SUCCESS;
			}
		} else {
			flag = false;
			message = "Incorrect password.";
			return SUCCESS;
		}

	}

	public String createPatient() {
		message = "";
		flag = true;
		if (gender.equals("-1") || email.trim().equals("") || sin.trim().equals("") || firstname.trim().equals("")
				|| lastname.trim().equals("") || date.trim().equals("") || phoneNum.trim().equals("")
				|| cellphone.trim().equals("") || address.trim().equals("") || postalCode.trim().equals("")
				|| currentHealth.trim().equals("") || ohip.trim().equals("") || defaultDoctor.trim().equals("")) {
			flag = false;
			message += "All fields are required.<br />";
		}
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(email.trim());
		Pattern patternPostal = Pattern.compile(POSTALCODE_PATTERN);
		Matcher matcherPostal = patternPostal.matcher(postalCode.trim());
		Pattern patternPhone = Pattern.compile(PHONE_PATTERN);
		Matcher matcherPhone = patternPhone.matcher(phoneNum.trim());
		Matcher matcherCellP = patternPhone.matcher(cellphone.trim());
		Pattern patternSin = Pattern.compile(SIN_PATTERN);
		Matcher matcherSin = patternSin.matcher(sin.trim());
		Pattern patternOhip = Pattern.compile(OHIP_PATTERN);
		Matcher matcherOhip = patternOhip.matcher(ohip.trim());
		if (!matcher.matches()) {
			flag = false;
			message += "The email is not valid.<br />";
		}
		if (!matcherPostal.matches()) {
			flag = false;
			message += "The postal code is not valid.<br />";
		}
		if (!matcherPhone.matches()) {
			flag = false;
			message += "The phone number is not valid.<br />";
		}
		if (!matcherCellP.matches()) {
			flag = false;
			message += "The cellphone number is not valid.<br />";
		}
		if (!matcherSin.matches()) {
			flag = false;
			message += "The Social Insurance Number is not valid.<br />";
		}
		if (!matcherOhip.matches()) {
			flag = false;
			message += "The health number is not valid.<br />";
		}
		if (!staffService.checkAvailability(email.trim())) {
			flag = false;
			message += "The email has been used.<br />";
		}
		if (!staffService.checkSinUnique(hospitalUtil.encrypt(sin.trim()))) {
			flag = false;
			message += "The Social Insurance Number has been used.<br />";
		}
		if (!staffService.checkOhipUnique(hospitalUtil.encrypt(ohip).trim())) {
			flag = false;
			message += "The health number has been used.<br />";
		}
		String wrappedDoctorId = defaultDoctor.trim();
		long doctorId = -1;
		EmpInfoModel emp = new EmpInfoModel();
		if (!wrappedDoctorId.equals("")) {
			doctorId = hospitalUtil.deIdWrapper(wrappedDoctorId, (byte) 1);
		}
		if (doctorId == -2) {
			flag = false;
			message += "Doctor id is not valid.<br />";
		} else {
			emp = staffService.getDefaultDoctor(doctorId);
			if (emp == null) {
				flag = false;
				message += "The doctor does not exist.<br />";
			}
		}

		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		Date parsedDate = null;
		try {
			parsedDate = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			flag = false;
			message += "Date of birth is not valid.<br />";
		}
		if (parsedDate != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(parsedDate);
			if (c.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()) {
				flag = false;
				message += "The date of birth should not come after the current time.<br />";
			}
		}
		if (flag == false) {
			return SUCCESS;
		}

		loginInfo.setUsername(email.trim());
		loginInfo.setPassword(hospitalUtil.encrypt(sin.trim()));
		patientInfo.setRole((byte) 0);
		patientInfo.setFirstname(firstname.trim());
		patientInfo.setLastname(lastname.trim());
		patientInfo.setEmail(email.trim());
		if (parsedDate != null) {
			patientInfo.setDateOfBirth(parsedDate);
		}
		patientInfo.setSin(hospitalUtil.encrypt(sin.trim()));
		patientInfo.setOhip(hospitalUtil.encrypt(ohip.trim()));
		if (gender.equals("male")) {
			patientInfo.setGender('m');
		} else {
			patientInfo.setGender('f');
		}
		patientInfo.setPhonenum(phoneNum.trim());
		patientInfo.setCellphone(cellphone.trim());
		patientInfo.setAddress(address.trim());
		patientInfo.setPostalCode(postalCode.trim());

		patientInfo.setDefaultDoctor(doctorId);
		patientInfo.setCurrentHealth(currentHealth.trim());

		Set<EmpInfoModel> grantedDoctors = new HashSet<EmpInfoModel>();
		grantedDoctors.add(emp);
		patientInfo.setGrantedDoctors(grantedDoctors);

		boolean result = staffService.createPatient(loginInfo, patientInfo);
		if (result) {
			flag = true;
			message = "Create the patient successfully.";
			return SUCCESS;
		} else {
			flag = false;
			message = "Fail to create the new patient.";
			return SUCCESS;
		}
	}

	public String viewRecord() {
		return SUCCESS;
	}

	public String searchResult() {
		String wrappedUserId = searchUserId.trim();
		long userId = -1;
		if (!wrappedUserId.equals("")) {
			userId = hospitalUtil.deIdWrapper(wrappedUserId, (byte) 0);
		}
		String firstname = searchFirstname.trim();
		String lastname = searchLastname.trim();
		if (userId == -1 && firstname.equals("") && lastname.equals("")) {
			patientSearchResult.clear();
			return SUCCESS;
		}
		patientSearchResult = staffService.getPatientResult(userId, firstname, lastname);
		Iterator<PatientInfoModel> it = patientSearchResult.iterator();
		PatientInfoModel tmp = new PatientInfoModel();
		while (it.hasNext()) {
			tmp = it.next();
			userId = tmp.getUserId();
			tmp.setUserId(hospitalUtil.idWrapper(userId, (byte) 0));
		}
		return SUCCESS;
	}

	public String goBackToStaffHome() {
		return SUCCESS;
	}

	public String newAppointment() {
		return SUCCESS;
	}

	public String appointPatientSearch() {
		String wrappedUserId = appointPatientId.trim();
		long userId = -1;
		if (!wrappedUserId.equals("")) {
			userId = hospitalUtil.deIdWrapper(wrappedUserId, (byte) 0);
		}
		String firstname = appointPatientFirstname.trim();
		String lastname = appointPatientLastname.trim();
		if (userId == -1 && firstname.equals("") && lastname.equals("")) {
			appointPatientSearchResult.clear();
			return SUCCESS;
		}
		appointPatientSearchResult = staffService.getAppointPatientResult(userId, firstname, lastname);
		Iterator<PatientInfoModel> it = appointPatientSearchResult.iterator();
		PatientInfoModel tmp = new PatientInfoModel();
		while (it.hasNext()) {
			tmp = it.next();
			userId = tmp.getUserId();
			tmp.setUserId(hospitalUtil.idWrapper(userId, (byte) 0));
		}
		return SUCCESS;
	}

	public String createAppointment() {
		flag = true;
		message = "";
		if (confirmedPatientId.trim().equals("") || confirmedDocId.trim().equals("") || date.trim().equals("")
				|| time.trim().equals("")) {
			flag = false;
			message += "All fields are required.<br />";
		}
		String wrappedPatientId = confirmedPatientId.trim();
		long patientId = -1;
		if (!wrappedPatientId.equals("")) {
			patientId = hospitalUtil.deIdWrapper(wrappedPatientId, (byte) 0);
		}
		if (patientId == -2) {
			flag = false;
			message += "Patient id is not valid.<br />";
		} else {
			boolean result = staffService.checkPatientExist(patientId);
			if (result == false) {
				flag = false;
				message += "The patient does not exist.<br />";
			}
		}
		String wrappedDoctorId = confirmedDocId.trim();
		long doctorId = -1;
		EmpInfoModel emp = new EmpInfoModel();
		if (!wrappedDoctorId.equals("")) {
			doctorId = hospitalUtil.deIdWrapper(wrappedDoctorId, (byte) 1);
		}
		if (doctorId == -2) {
			flag = false;
			message += "Doctor id is not valid.<br />";
		} else {
			emp = staffService.getDefaultDoctor(doctorId);
			if (emp == null) {
				flag = false;
				message += "The doctor does not exist.<br />";
			}
		}
		Calendar c = Calendar.getInstance();
		if (!date.trim().equals("") && !time.trim().equals("")) {
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
			Date parsedDate = null;
			try {
				parsedDate = sdf.parse(date + " " + time);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (parsedDate != null) {
				c.setTime(parsedDate);
			}
			if (c.getTimeInMillis() <= Calendar.getInstance().getTimeInMillis()) {
				flag = false;
				message += "Appointment time should come after the current time.<br />";
			}
		}
		if (false == flag) {
			return SUCCESS;
		}
		appointment.setPatientId(Long.valueOf(patientId));
		appointment.setDoctorId(Long.valueOf(doctorId));
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		long currentUserId = (long) ra.getAttribute("currentUserId", RequestAttributes.SCOPE_SESSION);
		appointment.setStaffId(Long.valueOf(currentUserId));
		appointment.setAppointmentTime(c.getTimeInMillis());
		boolean result = staffService.createAppointment(appointment);
		if (result) {
			flag = true;
			message = "Create the appointment successfully.";
			return SUCCESS;
		} else {
			flag = false;
			message = "Fail to create the appointment.";
			return SUCCESS;
		}

	}

	public String appointDocSearch() {
		String wrappedUserId = appointDocId.trim();
		long userId = -1;
		if (!wrappedUserId.equals("")) {
			userId = hospitalUtil.deIdWrapper(wrappedUserId, (byte) 1);
		}
		String firstname = appointDocFirstname.trim();
		String lastname = appointDocLastname.trim();
		if (userId == -1 && firstname.equals("") && lastname.equals("")) {
			appointDocSearchResult.clear();
			return SUCCESS;
		}
		appointDocSearchResult = staffService.getAppointDocResult(userId, firstname, lastname);
		Iterator<EmpInfoModel> it = appointDocSearchResult.iterator();
		EmpInfoModel tmp = new EmpInfoModel();
		while (it.hasNext()) {
			tmp = it.next();
			userId = tmp.getUserId();
			tmp.setUserId(hospitalUtil.idWrapper(userId, (byte) 1));
		}
		return SUCCESS;
	}

	public String docSchedule() {
		String wrappedUserId = scheduleDocId.trim();
		long userId = -1;
		if (!wrappedUserId.equals("")) {
			userId = hospitalUtil.deIdWrapper(wrappedUserId, (byte) 1);
		}
		docSchedules = staffService.getDocSchedules(userId);
		Iterator<DocScheduleModel> it = docSchedules.iterator();
		DocScheduleModel tmp = new DocScheduleModel();
		long patientId, doctorId, staffId;
		while (it.hasNext()) {
			tmp = it.next();
			patientId = tmp.getPatientId();
			tmp.setPatientId(hospitalUtil.idWrapper(patientId, (byte) 0));
			doctorId = tmp.getDoctorId();
			tmp.setDoctorId(hospitalUtil.idWrapper(doctorId, (byte) 1));
			staffId = tmp.getStaffId();
			tmp.setStaffId(hospitalUtil.idWrapper(staffId, (byte) 2));
		}
		return SUCCESS;
	}

	public String recordList() {
		String wrappedUserId = recordListPatientId.trim();
		long userId = -1;
		if (!wrappedUserId.equals("")) {
			userId = hospitalUtil.deIdWrapper(wrappedUserId, (byte) 0);
		}
		recordDetailList = staffService.getRecordDetailList(userId);
		Iterator<RecordDetailModel> it = recordDetailList.iterator();
		RecordDetailModel tmp = new RecordDetailModel();
		long patientId, doctorId;
		while (it.hasNext()) {
			tmp = it.next();
			patientId = tmp.getPatientId();
			tmp.setPatientId(hospitalUtil.idWrapper(patientId, (byte) 0));
			doctorId = tmp.getDoctorId();
			tmp.setDoctorId(hospitalUtil.idWrapper(doctorId, (byte) 1));
		}
		return SUCCESS;
	}

	public String searchAppointment() {
		String wrappedPatientId = confirmedPatientId.trim();
		long patientId = -1;
		if (!wrappedPatientId.equals("")) {
			patientId = hospitalUtil.deIdWrapper(wrappedPatientId, (byte) 0);
		}
		String wrappedDoctorId = confirmedDocId.trim();
		long doctorId = -1;
		if (!wrappedDoctorId.equals("")) {
			doctorId = hospitalUtil.deIdWrapper(wrappedDoctorId, (byte) 1);
		}
		long appointId = -1;
		if (!appointmentId.trim().equals("")) {
			appointId = Long.valueOf(appointmentId);
		}
		docSchedules = staffService.getAppointmentList(appointId, patientId, doctorId);
		Iterator<DocScheduleModel> it = docSchedules.iterator();
		DocScheduleModel tmp = new DocScheduleModel();
		long wpatientId, wdoctorId, wstaffId;
		while (it.hasNext()) {
			tmp = it.next();
			wpatientId = tmp.getPatientId();
			tmp.setPatientId(hospitalUtil.idWrapper(wpatientId, (byte) 0));
			wdoctorId = tmp.getDoctorId();
			tmp.setDoctorId(hospitalUtil.idWrapper(wdoctorId, (byte) 1));
			wstaffId = tmp.getStaffId();
			tmp.setStaffId(hospitalUtil.idWrapper(wstaffId, (byte) 2));
		}
		return SUCCESS;
	}

	public String udAppointment() {
		return SUCCESS;
	}

	public String updateAppointment() {
		flag = true;
		message = "";
		if (confirmedPatientId.trim().equals("") || confirmedDocId.trim().equals("") || date.trim().equals("")
				|| time.trim().equals("")) {
			flag = false;
			message += "All fields are required.<br />";
		}
		String wrappedPatientId = confirmedPatientId.trim();
		long patientId = -1;
		if (!wrappedPatientId.equals("")) {
			patientId = hospitalUtil.deIdWrapper(wrappedPatientId, (byte) 0);
		}
		if (patientId == -2) {
			flag = false;
			message += "Patient id is not valid.<br />";
		} else {
			boolean result = staffService.checkPatientExist(patientId);
			if (result == false) {
				flag = false;
				message += "The patient does not exist.<br />";
			}
		}
		String wrappedDoctorId = confirmedDocId.trim();
		long doctorId = -1;
		EmpInfoModel emp = new EmpInfoModel();
		if (!wrappedDoctorId.equals("")) {
			doctorId = hospitalUtil.deIdWrapper(wrappedDoctorId, (byte) 1);
		}
		if (doctorId == -2) {
			flag = false;
			message += "Doctor id is not valid.<br />";
		} else {
			emp = staffService.getDefaultDoctor(doctorId);
			if (emp == null) {
				flag = false;
				message += "The doctor does not exist.<br />";
			}
		}
		Calendar c = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
		Date parsedDate = null;
		try {
			parsedDate = sdf.parse(date + " " + time);
		} catch (ParseException e) {
			e.printStackTrace();
			flag = false;
			message += "Appointment time is not valid.<br />";
		}
		if (parsedDate != null) {
			c.setTime(parsedDate);
		}
		if (c.getTimeInMillis() <= Calendar.getInstance().getTimeInMillis()) {
			flag = false;
			message += "Appointment time should come after the current time.<br />";
		}
		if (flag == false) {
			return SUCCESS;
		}
		appointment.setAppointmentId(Long.valueOf(updateAppointId));
		appointment.setPatientId(Long.valueOf(patientId));
		appointment.setDoctorId(Long.valueOf(doctorId));
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		long currentUserId = (long) ra.getAttribute("currentUserId", RequestAttributes.SCOPE_SESSION);
		appointment.setStaffId(Long.valueOf(currentUserId));
		appointment.setAppointmentTime(c.getTimeInMillis());
		boolean result = staffService.updateAppointment(appointment);
		if (result) {
			flag = true;
			message = "Update the appointment successfully.";
			String wrappedRelistPatientId = relistPatientId.trim();
			long relistPatientId = -1;
			if (!wrappedRelistPatientId.equals("")) {
				relistPatientId = hospitalUtil.deIdWrapper(wrappedRelistPatientId, (byte) 0);
			}
			String wrappedRelistDoctorId = relistDocId.trim();
			long relistDoctorId = -1;
			if (!wrappedRelistDoctorId.equals("")) {
				relistDoctorId = hospitalUtil.deIdWrapper(wrappedRelistDoctorId, (byte) 1);
			}
			long appointId = -1;
			if (!relistAppointmentId.trim().equals("")) {
				appointId = Long.valueOf(relistAppointmentId.trim());
			}
			docSchedules = staffService.getAppointmentList(appointId, relistPatientId, relistDoctorId);
			Iterator<DocScheduleModel> it = docSchedules.iterator();
			DocScheduleModel tmp = new DocScheduleModel();
			long wpatientId, wdoctorId, wstaffId;
			while (it.hasNext()) {
				tmp = it.next();
				wpatientId = tmp.getPatientId();
				tmp.setPatientId(hospitalUtil.idWrapper(wpatientId, (byte) 0));
				wdoctorId = tmp.getDoctorId();
				tmp.setDoctorId(hospitalUtil.idWrapper(wdoctorId, (byte) 1));
				wstaffId = tmp.getStaffId();
				tmp.setStaffId(hospitalUtil.idWrapper(wstaffId, (byte) 2));
			}
			return SUCCESS;
		} else {
			flag = false;
			message = "Fail to update the appointment.";
			return SUCCESS;
		}
	}

	public String deleteAppointment() {
		boolean result = staffService.deleteAppointment(Long.valueOf(deleteAppointId));
		if (result) {
			flag = true;
			message = "Delete the appointment successfully.";
			return searchAppointment();
		} else {
			flag = false;
			message = "Fail to delete the appointment.";
			return SUCCESS;
		}
	}

	public String updatePatientInfo() {
		message = "";
		flag = true;
		if (gender.equals("-1") || firstname.trim().equals("") || lastname.trim().equals("") || date.trim().equals("")
				|| phoneNum.trim().equals("") || cellphone.trim().equals("") || address.trim().equals("")
				|| postalCode.trim().equals("") || currentHealth.trim().equals("") || email.trim().equals("")) {
			flag = false;
			message += "All fields are required.<br />";
		}
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(email.trim());
		Pattern patternPostal = Pattern.compile(POSTALCODE_PATTERN);
		Matcher matcherPostal = patternPostal.matcher(postalCode.trim());
		Pattern patternPhone = Pattern.compile(PHONE_PATTERN);
		Matcher matcherPhone = patternPhone.matcher(phoneNum.trim());
		Matcher matcherCellP = patternPhone.matcher(cellphone.trim());
		if (!matcher.matches()) {
			flag = false;
			message += "The email is not valid.<br />";
		}
		if (!matcherPostal.matches()) {
			flag = false;
			message += "The postal code is not valid.<br />";
		}
		if (!matcherPhone.matches()) {
			flag = false;
			message += "The phone number is not valid.<br />";
		}
		if (!matcherCellP.matches()) {
			flag = false;
			message += "The cellphone number is not valid.<br />";
		}
		String wrappedPatientId = updatePatientId.trim();
		long patientId = -1;
		if (!wrappedPatientId.equals("")) {
			patientId = hospitalUtil.deIdWrapper(wrappedPatientId, (byte) 0);
		}
		if (patientId == -2) {
			flag = false;
			message += "Patient id is not valid.<br />";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
		Date parsedDate = null;
		try {
			parsedDate = sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
			flag = false;
			message += "Date of birth is not valid.<br />";
		}
		if (parsedDate != null) {
			Calendar c = Calendar.getInstance();
			c.setTime(parsedDate);
			if (c.getTimeInMillis() > Calendar.getInstance().getTimeInMillis()) {
				flag = false;
				message += "The date of birth should not come after the current time.<br />";
			}
		}

		if (flag == false) {
			return SUCCESS;
		}
		boolean res = staffService.updateUsername(email.trim(), patientId);
		if (!res) {
			flag = false;
			message = "Fail to update the patient information.";
			return SUCCESS;
		}
		patientInfo.setUserId(Long.valueOf(patientId));
		patientInfo.setFirstname(firstname.trim());
		patientInfo.setLastname(lastname.trim());
		if (parsedDate != null) {
			patientInfo.setDateOfBirth(parsedDate);
		}
		if (gender.equals("male")) {
			patientInfo.setGender('m');
		} else {
			patientInfo.setGender('f');
		}
		patientInfo.setPhonenum(phoneNum.trim());
		patientInfo.setCellphone(cellphone.trim());
		patientInfo.setAddress(address.trim());
		patientInfo.setPostalCode(postalCode.trim());
		patientInfo.setCurrentHealth(currentHealth.trim());

		boolean result = staffService.updatePatient(patientInfo);
		if (result) {
			flag = true;
			message = "Update the patient information successfully.";
			return SUCCESS;
		} else {
			flag = false;
			message = "Fail to update the patient information.";
			return SUCCESS;
		}
	}

	public String allPatients() {
		patientSearchResult = staffService.getAllPatients();
		Iterator<PatientInfoModel> it = patientSearchResult.iterator();
		PatientInfoModel tmp = new PatientInfoModel();
		long userId = -1;
		while (it.hasNext()) {
			tmp = it.next();
			userId = tmp.getUserId();
			tmp.setUserId(hospitalUtil.idWrapper(userId, (byte) 0));
		}
		return SUCCESS;
	}

	public String searchRecord() {
		flag = true;
		message = "";
		String wrappedPatientId = recordPatientId.trim();
		long patientId = -1;
		if (!wrappedPatientId.equals("")) {
			patientId = hospitalUtil.deIdWrapper(wrappedPatientId, (byte) 0);
		}
		if (patientId == -1) {
			flag = false;
			message += "Patient id cannot be empty for advanced search.<br />";
		}
		long recordTimeStart = -1;
		if (!startDate.trim().equals("")) {
			Calendar cStart = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
			Date parsedDate = null;
			try {
				parsedDate = sdf.parse(startDate + " " + "00:00");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (parsedDate != null) {
				cStart.setTime(parsedDate);
			}
			recordTimeStart = cStart.getTimeInMillis();
		}
		long recordTimeEnd = -1;
		if (!endDate.trim().equals("")) {
			Calendar cEnd = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
			Date parsedDate = null;
			try {
				parsedDate = sdf.parse(endDate + " " + "00:00");
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if (parsedDate != null) {
				cEnd.setTime(parsedDate);
			}
			recordTimeEnd = cEnd.getTimeInMillis() + 86400000;
		}
		if (recordTimeStart != -1 && recordTimeEnd != -1 && recordTimeStart >= recordTimeEnd) {
			flag = false;
			message += "The start time should not come after the end time.<br />";
		}
		if (false == flag) {
			return SUCCESS;
		}
		recordDetailList = staffService.searchRecord(patientId, recordTimeStart, recordTimeEnd, recordDiagnosis,
				recordDrug, recordComment);
		Iterator<RecordDetailModel> it = recordDetailList.iterator();
		RecordDetailModel tmp = new RecordDetailModel();
		long wpatientId, wdoctorId;
		while (it.hasNext()) {
			tmp = it.next();
			wpatientId = tmp.getPatientId();
			tmp.setPatientId(hospitalUtil.idWrapper(wpatientId, (byte) 0));
			wdoctorId = tmp.getDoctorId();
			tmp.setDoctorId(hospitalUtil.idWrapper(wdoctorId, (byte) 1));
			flag = true;
		}
		flag = true;
		return SUCCESS;
	}

	public String updatePatientInfoPage() {
		return SUCCESS;
	}

	public PatientInfoModel getPatientInfo() {
		return patientInfo;
	}

	public void setPatientInfo(PatientInfoModel patientInfo) {
		this.patientInfo = patientInfo;
	}

	public String getFirstname() {
		return firstname;
	}

	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	public String getLastname() {
		return lastname;
	}

	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	public String getSin() {
		return sin;
	}

	public void setSin(String sin) {
		this.sin = sin;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public String getPhoneNum() {
		return phoneNum;
	}

	public void setPhoneNum(String phoneNum) {
		this.phoneNum = phoneNum;
	}

	public String getCellphone() {
		return cellphone;
	}

	public void setCellphone(String cellphone) {
		this.cellphone = cellphone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getPostalCode() {
		return postalCode;
	}

	public void setPostalCode(String postalCode) {
		this.postalCode = postalCode;
	}

	public String getOhip() {
		return ohip;
	}

	public void setOhip(String ohip) {
		this.ohip = ohip;
	}

	public String getDefaultDoctor() {
		return defaultDoctor;
	}

	public void setDefaultDoctor(String defaultDoctor) {
		this.defaultDoctor = defaultDoctor;
	}

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	public String getMonth() {
		return month;
	}

	public void setMonth(String month) {
		this.month = month;
	}

	public String getDay() {
		return day;
	}

	public void setDay(String day) {
		this.day = day;
	}

	public String getCurrentHealth() {
		return currentHealth;
	}

	public void setCurrentHealth(String currentHealth) {
		this.currentHealth = currentHealth;
	}

	public StaffService getStaffService() {
		return staffService;
	}

	public void setStaffService(StaffService staffService) {
		this.staffService = staffService;
	}

	public LoginModel getLoginInfo() {
		return loginInfo;
	}

	public void setLoginInfo(LoginModel loginInfo) {
		this.loginInfo = loginInfo;
	}

	public String getSearchUserId() {
		return searchUserId;
	}

	public void setSearchUserId(String searchUserId) {
		this.searchUserId = searchUserId;
	}

	public String getSearchFirstname() {
		return searchFirstname;
	}

	public void setSearchFirstname(String searchFirstname) {
		this.searchFirstname = searchFirstname;
	}

	public String getSearchLastname() {
		return searchLastname;
	}

	public void setSearchLastname(String searchLastname) {
		this.searchLastname = searchLastname;
	}

	public List<PatientInfoModel> getPatientSearchResult() {
		return patientSearchResult;
	}

	public void setPatientSearchResult(List<PatientInfoModel> patientSearchResult) {
		this.patientSearchResult = patientSearchResult;
	}

	public String getAppointUserId() {
		return appointPatientId;
	}

	public void setAppointUserId(String appointPatientId) {
		this.appointPatientId = appointPatientId;
	}

	public String getAppointFirstname() {
		return appointPatientFirstname;
	}

	public void setAppointFirstname(String appointPatientFirstname) {
		this.appointPatientFirstname = appointPatientFirstname;
	}

	public String getAppointLastname() {
		return appointPatientLastname;
	}

	public void setAppointLastname(String appointPatientLastname) {
		this.appointPatientLastname = appointPatientLastname;
	}

	public List<PatientInfoModel> getAppointPatientSearchResult() {
		return appointPatientSearchResult;
	}

	public void setAppointPatientSearchResult(List<PatientInfoModel> appointPatientSearchResult) {
		this.appointPatientSearchResult = appointPatientSearchResult;
	}

	public String getAppointPatientId() {
		return appointPatientId;
	}

	public void setAppointPatientId(String appointPatientId) {
		this.appointPatientId = appointPatientId;
	}

	public String getAppointPatientFirstname() {
		return appointPatientFirstname;
	}

	public void setAppointPatientFirstname(String appointPatientFirstname) {
		this.appointPatientFirstname = appointPatientFirstname;
	}

	public String getAppointPatientLastname() {
		return appointPatientLastname;
	}

	public void setAppointPatientLastname(String appointPatientLastname) {
		this.appointPatientLastname = appointPatientLastname;
	}

	public String getAppointDocId() {
		return appointDocId;
	}

	public void setAppointDocId(String appointDocId) {
		this.appointDocId = appointDocId;
	}

	public String getAppointDocFirstname() {
		return appointDocFirstname;
	}

	public void setAppointDocFirstname(String appointDocFirstname) {
		this.appointDocFirstname = appointDocFirstname;
	}

	public String getAppointDocLastname() {
		return appointDocLastname;
	}

	public void setAppointDocLastname(String appointDocLastname) {
		this.appointDocLastname = appointDocLastname;
	}

	public List<EmpInfoModel> getAppointDocSearchResult() {
		return appointDocSearchResult;
	}

	public void setAppointDocSearchResult(List<EmpInfoModel> appointDocSearchResult) {
		this.appointDocSearchResult = appointDocSearchResult;
	}

	public String getConfirmedPatientId() {
		return confirmedPatientId;
	}

	public void setConfirmedPatientId(String confirmedPatientId) {
		this.confirmedPatientId = confirmedPatientId;
	}

	public String getConfirmedDocId() {
		return confirmedDocId;
	}

	public void setConfirmedDocId(String confirmedDocId) {
		this.confirmedDocId = confirmedDocId;
	}

	public String getScheduleDocId() {
		return scheduleDocId;
	}

	public void setScheduleDocId(String scheduleDocId) {
		this.scheduleDocId = scheduleDocId;
	}

	public List<DocScheduleModel> getDocSchedules() {
		return docSchedules;
	}

	public void setDocSchedules(List<DocScheduleModel> docSchedules) {
		this.docSchedules = docSchedules;
	}

	public String getHour() {
		return hour;
	}

	public void setHour(String hour) {
		this.hour = hour;
	}

	public String getMinute() {
		return minute;
	}

	public void setMinute(String minute) {
		this.minute = minute;
	}

	public AppointmentModel getAppointment() {
		return appointment;
	}

	public void setAppointment(AppointmentModel appointment) {
		this.appointment = appointment;
	}

	public String getRecordListPatientId() {
		return recordListPatientId;
	}

	public void setRecordListPatientId(String recordListPatientId) {
		this.recordListPatientId = recordListPatientId;
	}

	public List<RecordDetailModel> getRecordDetailList() {
		return recordDetailList;
	}

	public void setRecordDetailList(List<RecordDetailModel> recordDetailList) {
		this.recordDetailList = recordDetailList;
	}

	public String getAppointmentId() {
		return appointmentId;
	}

	public void setAppointmentId(String appointmentId) {
		this.appointmentId = appointmentId;
	}

	public String getUpdateAppointId() {
		return updateAppointId;
	}

	public void setUpdateAppointId(String updateAppointId) {
		this.updateAppointId = updateAppointId;
	}

	public String getDeleteAppointId() {
		return deleteAppointId;
	}

	public void setDeleteAppointId(String deleteAppointId) {
		this.deleteAppointId = deleteAppointId;
	}

	public String getUpdatePatientId() {
		return updatePatientId;
	}

	public void setUpdatePatientId(String updatePatientId) {
		this.updatePatientId = updatePatientId;
	}

	public String getRecordPatientId() {
		return recordPatientId;
	}

	public void setRecordPatientId(String recordPatientId) {
		this.recordPatientId = recordPatientId;
	}

	public String getYearStart() {
		return yearStart;
	}

	public void setYearStart(String yearStart) {
		this.yearStart = yearStart;
	}

	public String getMonthStart() {
		return monthStart;
	}

	public void setMonthStart(String monthStart) {
		this.monthStart = monthStart;
	}

	public String getDayStart() {
		return dayStart;
	}

	public void setDayStart(String dayStart) {
		this.dayStart = dayStart;
	}

	public String getRecordDiagnosis() {
		return recordDiagnosis;
	}

	public void setRecordDiagnosis(String recordDiagnosis) {
		this.recordDiagnosis = recordDiagnosis;
	}

	public String getRecordDrug() {
		return recordDrug;
	}

	public void setRecordDrug(String recordDrug) {
		this.recordDrug = recordDrug;
	}

	public String getRecordComment() {
		return recordComment;
	}

	public void setRecordComment(String recordComment) {
		this.recordComment = recordComment;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getRelistAppointmentId() {
		return relistAppointmentId;
	}

	public void setRelistAppointmentId(String relistAppointmentId) {
		this.relistAppointmentId = relistAppointmentId;
	}

	public String getRelistPatientId() {
		return relistPatientId;
	}

	public void setRelistPatientId(String relistPatientId) {
		this.relistPatientId = relistPatientId;
	}

	public String getRelistDocId() {
		return relistDocId;
	}

	public void setRelistDocId(String relistDocId) {
		this.relistDocId = relistDocId;
	}

	public String getYearEnd() {
		return yearEnd;
	}

	public void setYearEnd(String yearEnd) {
		this.yearEnd = yearEnd;
	}

	public String getMonthEnd() {
		return monthEnd;
	}

	public void setMonthEnd(String monthEnd) {
		this.monthEnd = monthEnd;
	}

	public String getDayEnd() {
		return dayEnd;
	}

	public void setDayEnd(String dayEnd) {
		this.dayEnd = dayEnd;
	}

	public String getDate() {
		return date;
	}

	public void setDate(String date) {
		this.date = date;
	}

	public String getTime() {
		return time;
	}

	public void setTime(String time) {
		this.time = time;
	}

	public String getStartDate() {
		return startDate;
	}

	public void setStartDate(String startDate) {
		this.startDate = startDate;
	}

	public String getEndDate() {
		return endDate;
	}

	public void setEndDate(String endDate) {
		this.endDate = endDate;
	}

	public HospitalUtil getHospitalUtil() {
		return hospitalUtil;
	}

	public void setHospitalUtil(HospitalUtil hospitalUtil) {
		this.hospitalUtil = hospitalUtil;
	}

	public String getOrigPassword() {
		return origPassword;
	}

	public void setOrigPassword(String origPassword) {
		this.origPassword = origPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getConfirmedNewPassword() {
		return confirmedNewPassword;
	}

	public void setConfirmedNewPassword(String confirmedNewPassword) {
		this.confirmedNewPassword = confirmedNewPassword;
	}

}
